package Redis

import (
	"fmt"
	"source-admin-go/pkg/e"
	"source-admin-go/src/config"
	"time"

	"github.com/go-redis/redis"
)

var Client *redis.Client

func init() {
	redisConfig := config.Server.Database.Redis
	client := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%v:%v", redisConfig.Addr, redisConfig.Port),
		Password: redisConfig.Password,
		DB:       redisConfig.Db,
	})
	Client = client
}

func ServiceValidation() {
	_, err := Client.Ping().Result()
	if err != nil {
		message := fmt.Sprintf("Redis service failed to start:【%v】", err)
		e.ErrorLogPrintln(message)
		return
	}
	e.SuccessLogPrintln("The Redis service is open")
}

func GetValueByKey(key string) string {
	val, err := Client.Get(key).Result()
	if err != nil {
		e.WarmingLogPrintln(fmt.Sprintf("Redis service retrieval error:【%v】", err.Error()))
		return ""
	}
	return val
}

func SetKeyValue(key string, value string, t ...time.Duration) error {
	var s time.Duration
	if len(t) > 0 && t[0] != 0 {
		s = t[0]
	} else {
		s = 10
	}
	err := Client.Set(key, value, s*time.Second).Err()
	if err != nil {
		e.WarmingLogPrintln(fmt.Sprintf("Redis service storage error:【%v】", err.Error()))
	}
	return err
}
